/**
 * FileName:     StringToDateConverter.java
 * CreationDate: 2014年5月3日
 * Author:       qiujy
 * EMail:        qjyong@gmail.com
 * Site:         http://www.itvk.cn
 * CopyRight: ITVK.CN All Recieves.
 */
package gx.web.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

/**
 * 字符串-->java.util.Date的自定义转换器
 */
public class StringToDateConverter implements Converter<String, Date> {

	public static final DateFormat DF_LONG2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final DateFormat DF_LONG = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	public static final DateFormat DF_SHORT = new SimpleDateFormat("yyyy-MM-dd");
	public static final DateFormat DF_YEAR = new SimpleDateFormat("yyyy");
	public static final DateFormat DF_MONTH = new SimpleDateFormat("yyyy-MM");
	
	
	public static final int LONG_DATE = 16;
	public static final int SHORT_DATE = 10;

	public static final int YEAR_DATE = 4;

	public static final int MONTH_DATE = 7;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.core.convert.converter.Converter#convert(java.lang
	 * .Object)
	 */
	public Date convert(String source) {
		
		if (!StringUtils.hasText(source)) {
			return null;
		}
		source = source.trim();
		Date date = null;
		try {
			if (source.length() <= YEAR_DATE) {
				date = DF_YEAR.parse(source);
			} else if (source.length() <= MONTH_DATE) {
				date = DF_MONTH.parse(source);
			} else if (source.length() <= SHORT_DATE) {
				date = DF_SHORT.parse(source);
			} else if (source.length() <= LONG_DATE) {
				date = DF_LONG.parse(source);
			} else {
				date = DF_LONG2.parse(source);
			}
		} catch (ParseException e) {
			IllegalArgumentException ee = new IllegalArgumentException("日期格式转换失败: " + e.getMessage());
			ee.initCause(e);
			throw ee;
		}
		return date;
	}

}
